<template>
  <div class="login-form mxauto white-bg">
    <h1 class="title">登录</h1>

    <el-form
      :rules="rules"
      :model="state.loginValidateForm"
      ref="ruleFormRef"
         @keyup.enter.native="submitForm(ruleFormRef)"
      class="ruleForm mt30"
    >
      <template v-if="signInType">
        <div>
          <el-form-item prop="username" class="mt30">
            <el-input
              type="text"
              placeholder="请输入"
              v-model="state.loginValidateForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item class="mt30" prop="password">
            <el-input
              show-password
              placeholder="输入密码"
              v-model="state.loginValidateForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
              <el-form-item prop="code" v-if="state.captchaEnabled">
        <el-input
          v-model="state.loginValidateForm.code"
          placeholder="验证码"
          style="width: 63%"
        >
        </el-input>
        <div class="login-code" >
          <img v-if="state.image" :src="state.image" @click="getCodeImage" class="login-code-img"/>
        </div>
      </el-form-item>
        </div>
      </template>
      <template v-else>
        <div>
          <el-form-item prop="email">
            <div class="aic">
              <el-input
                placeholder="输入邮箱"
                v-model="state.loginValidateForm.email"
              ></el-input>
              <el-button type="primary" @click="getCode" class="ml15">{{
                codeText
              }}</el-button>
            </div>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              placeholder="验证码"
              v-model="state.loginValidateForm.code"
              type="text"
            ></el-input>
          </el-form-item>
        </div>
      </template>
      <el-form-item class="mt30">
        <el-button
          type="primary"
          class="w100"
          :loading="loading"
          @click="submitForm(ruleFormRef)"
          >登录</el-button
        >
      </el-form-item>
      <el-form-item class="mt30">
        <div class="jcb aic w100">
          <el-button @click.native="handleGoregister">注册</el-button>
          <el-button @click.native="handleGoregister">忘记密码</el-button>
          <el-button @click.native="handleSignType">
            {{ signInType ? "邮箱登录" : "账户密码登录" }}</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  getCurrentInstance,
  defineComponent,
  onMounted,
} from "vue";
import getmd5 from "/@ts/plugins/md5";
import { useRouter, useRoute } from "vue-router";
import { store } from "/@ts/store";

import { MenuRouter } from "/@ts/router/routes";
import { async } from "@antv/x6/lib/registry/marker/async";
import { useFullLoading } from "/@ts/hooks/fullLoading";
import useRegular from "/@ts/hooks/regular";
import {
  ElMessage,
  ElNotification,
  FormInstance,
  FormRules,
} from "element-plus";
import {  
  getCodeImg
} from "/@ts/axios/urlApi/system";

let emit = defineEmits(["handleGoregister"]);
const router = useRouter();
const { openLoading, closeLoading } = useFullLoading();
const internalInstance = getCurrentInstance(); //获取当前实例
const ruleFormRef = ref<FormInstance>();
const { regEmail } = useRegular();
const handleGoregister = () => {
  emit("handleGoregister", true);
};
let codeText = ref("获取验证码");
let countdown: number = 60;
const setTime = () => {
  if (countdown == 0) {
    codeText.value = "获取验证码";
    countdown = 60; //60秒过后button上的文字初始化,计时器初始化;
    return;
  } else {
    codeText.value = countdown + "s";
    countdown--;
  }
  setTimeout(function() {
    setTime();
  }, 1000); //每1000毫秒执行一次
};
const getCode = () => {
  if (!regEmail(state.loginValidateForm.email)) {
    ElMessage.warning("请输入邮箱");
    return;
  }

  setTime();
  // getEmailCode({
  //   email: state.loginValidateForm.email,
  // }).then(() => {
  //   ElMessage.success("发送成功");
  // });
};
let signInType = ref(true); // false 账户密码 true 邮箱登录
const rules = reactive<FormRules>({
  email: [
    {
      required: true,
      type: "email",
      message: "请输入邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
    password: [
    { required: true, message: "密码不能为空" },
    { min: 5, max: 16, message: "长度在 5 到 16 个字符", trigger: "blur" },
  ],
  username: [
    { required: true, message: "账号不能为空" , trigger: "blur" },
  ],
});
/*
基本数据类型
引用数据类型（复杂类型） 个人建议 ref初始化变量 
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, 
ref定义的数据访问的时候要多一个.value
*/

let loading = ref(false); //登录按钮loading 动画bool值
const state = reactive({
  loginValidateForm: {
    username: "admin",
    password: "admin123",
    email: "",
    code: "",
    uuid:""
  },
  captchaEnabled:false,
  image:""
});
let FormRef: any = "";
const loginValidateFormRef = (el: any) => (FormRef = el);
/**
 * 用户登录
 */
const getCodeImage = () =>{
  getCodeImg()
  .then((res:any)=>{
    // console.log('res :>> ', res);
    state.captchaEnabled = res.captchaEnabled
    state.loginValidateForm.uuid = res.uuid;
    state.image ="data:image/gif;base64,"+ res.img
  })
}
const submitForm = async (formEl: FormInstance | undefined) => {
 

  if (!formEl) return
  await formEl?.validate()
      //通过数据校验
      openLoading()
      store.dispatch('loginModule/Login',state.loginValidateForm)
      .then(res=>{
         router.push("/");
      })
      .catch(() => {
        closeLoading()
            if (state.captchaEnabled) {
              getCodeImage();
              
            }
          });
   

};
const handleSignType = () => {
  signInType.value = !signInType.value;
};

onMounted(() => {
  closeLoading();
  getCodeImage()
});
</script>

<style scoped lang="scss">
.login-form {
  width: 400px;
  position: relative;
  left: 0;
  top: 100px;
  padding: 34px;
  border-radius: 7px;
  .title {
  }
}
.login-code {
  width: 33%;
  height: 38px;
  margin-left: 10px;
  img {
    cursor: pointer;
    height: 100%;
    vertical-align: middle;
  }
}
</style>
